package com.mygame.gateway.server.handler.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xinyue.network.message.stream.IGameMessage;
import com.xinyue.network.message.stream.IMessageHeader;
import com.xinyue.network.message.stream.TransferMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * 
 * @ClassName: EncodeHandler
 * @Description: 编码服务器向客户端发送的数据
 * @author: wgs
 * @date: 2019年4月7日 下午3:04:31
 */
public class EncodeHandler extends ChannelOutboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(EncodeHandler.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
       try {
    	if (msg instanceof IGameMessage) {
            IGameMessage message = (IGameMessage) msg;
            try {
                ByteBuf byteBuf = message.write();
                promise.setSuccess();
                ctx.write(byteBuf);
            } catch (Exception e) {
                logger.error("网关消息编码异常", e);
            }
        } else if (msg instanceof TransferMessage) {
            TransferMessage message = (TransferMessage) msg;
            IMessageHeader header = message.getHeader();
            ByteBuf totalSizeBuf = Unpooled.buffer(4);
            
            ByteBuf headerBuf = header.write();
            int totalSize =  4 + headerBuf.readableBytes();
            if(message.getBody() != null) {
            	totalSize += message.getBody().readableBytes();
            }
            totalSizeBuf.writeInt(totalSize);
            CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer();
            compositeByteBuf.addComponent(true, totalSizeBuf);
            compositeByteBuf.addComponent(true,headerBuf);
            if (message.getBody() != null) {
                compositeByteBuf.addComponent(true,message.getBody());
            }
            ctx.write(compositeByteBuf);
            promise.setSuccess();
        }
       }catch(Exception e) {
    	   logger.error("网关消息返回编码错误",e);
       }
    }
}
